package com.medical.literature.search.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.medical.literature.common.exception.BusinessException;
import com.medical.literature.common.vo.PageResult;
import com.medical.literature.search.dto.SearchRequest;
import com.medical.literature.search.dto.SearchResultItem;
import com.medical.literature.search.entity.SearchHistory;
import com.medical.literature.search.mapper.SearchHistoryMapper;
import com.medical.literature.search.mapper.SearchMapper;
import com.medical.literature.search.service.SearchService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 搜索服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SearchServiceImpl implements SearchService {
    
    private final SearchHistoryMapper searchHistoryMapper;
    private final SearchMapper searchMapper;

    @Override
    public PageResult<SearchResultItem> searchLiterature(SearchRequest request, Long userId) {
        log.info("执行文献搜索，用户ID: {}, 关键词: {}", userId, request.getKeyword());
        
        try {
            // 创建分页对象
            Page<SearchResultItem> page = new Page<>(request.getCurrent(), request.getSize());
            
            // 执行搜索
            IPage<SearchResultItem> resultPage = searchMapper.searchLiterature(page, request, userId);
            
            // 构造返回结果
            PageResult<SearchResultItem> searchResult = new PageResult<>(
                resultPage.getRecords(),
                resultPage.getTotal(),
                resultPage.getSize(),
                resultPage.getCurrent()
            );
            
            log.info("文献搜索完成，返回结果数: {}", searchResult.getRecords().size());
            return searchResult;
        } catch (Exception e) {
            log.error("文献搜索失败: {}", e.getMessage(), e);
            throw new BusinessException("搜索失败: " + e.getMessage());
        }
    }
    
    @Override
    public void saveSearchHistory(Long userId, String keyword) {
        if (!StringUtils.hasText(keyword)) {
            return;
        }
        
        // 创建搜索历史记录
        SearchHistory history = new SearchHistory();
        history.setUserId(userId);
        history.setKeyword(keyword);
        history.setResultCount(0); // 这里应该根据实际搜索结果数量设置
        history.setSearchTime(LocalDateTime.now());
        
        searchHistoryMapper.insert(history);
        log.info("保存搜索历史: 用户ID={}, 关键词={}", userId, keyword);
    }

    @Override
    public List<String> getRecentSearchHistory(Long userId, int limit) {
        // 查询用户最近的搜索历史
        return searchHistoryMapper.selectRecentSearchHistory(userId, limit);
    }

    @Override
    public void clearSearchHistory(Long userId) {
        searchHistoryMapper.deleteByUserId(userId);
        log.info("清除搜索历史: 用户ID={}", userId);
    }

    @Override
    public List<String> getHotKeywords(int limit) {
        // 查询热门搜索关键词
        return searchHistoryMapper.selectHotKeywords(limit);
    }
}